package server.jobs;

import static server.db.StmtHelper.db;

import it.sauronsoftware.cron4j.Scheduler;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import server.db.DatabaseFunctor;

import com.google.common.collect.Lists;
import com.google.inject.internal.Maps;

import feeds.FeedHelper;

public class PhotosJob {

	
	public static String url()
	{
		return "http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm?zws-id="+ID+"&zpid=";
	}
	
	public List<DatabaseFunctor<Integer>> getPhotos(String zpid)
	{
		String result = FeedHelper.getServiceResult(url()+zpid);
		
		
		List<DatabaseFunctor<Integer>> inserts = Lists.newLinkedList();

		
		JSONObject obj = new JSONObject();
		SAXParserFactory parser = SAXParserFactory.newInstance();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource ins = new InputSource();
			ins.setCharacterStream(new StringReader(result));
			Document doc = db.parse(ins);
			doc.getDocumentElement().normalize();
			Map<String,String> listingMap = Maps.newLinkedHashMap();
			NodeList nodeLst = doc.getElementsByTagName("response");
			for(int i=0; i<nodeLst.getLength();i++)
			{
				
				
				Node fstNode = nodeLst.item(i);
				 if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
					 fstNode.normalize();
					 Element fstElmnt = (Element) fstNode;
					 
					 NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("image");
					 if(fstNmElmntLst!=null && fstNmElmntLst.getLength()>0)
					 {
						 NodeList children = fstNmElmntLst.item(0).getChildNodes();
						 for(int j = 0; j < children.getLength(); j++)
						 {
							 Node propNode = children.item(j);
							 if (propNode.getNodeType() == Node.ELEMENT_NODE) {
								 Element propElem = (Element)propNode;
								
								 System.out.println(propElem.getTagName()+" "+propElem.getTextContent());
								 propElem.normalize();
								 listingMap.put(zpid+":"+j, propElem.getTextContent().replaceAll("\t", ""));
							 }
						 }
					 }
				 }
				
			}
			
			
			
			for(String key : listingMap.keySet())
				inserts.add(db("insert into photos (zillowID,image_url,photo_num)" +
					" values(")
					.addVariable(zpid)
					.addSql(",").addVariable(listingMap.get(key))
					.addSql(",").addVariable(key.substring(key.length()-1, key.length()))
					.addSql(")").executeUpdate());
			
			return inserts;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private static String ID = "X1-ZWz1bwyrxi651n_7aoby";

	public void initializeScheduler() {
		// Creates a Scheduler instance.
		Scheduler getListingsFromZillow = new Scheduler();
		// Schedule a task to be run every night at mid-night
		//"00 00 * * 1-7"
		
		getListingsFromZillow.schedule("* * * * *", new Runnable() {
			public void run() {
				try {
					List<DatabaseFunctor<Integer>> insertList = Lists.newLinkedList();
					for(String zillowID : db("select zillowID from alllist").collectStrings.unsafeGet().get("zillowID"))
					{
						List<DatabaseFunctor<Integer>> anotherList = getPhotos(zillowID);
						if(anotherList!=null)
							insertList.addAll(anotherList);
					}
					DatabaseFunctor.sequence(insertList).unsafeUpdate();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		// Starts the scheduler.
		getListingsFromZillow.start();
	}
}
